#!/bin/bash

SWNAME=mysql-server

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

if [ "${action}" == "卸载" ]; then
	apt-get autoremove --purge -y ${SWNAME}
	rm -rf /usr/bin/mysqld_passwd_root
else
	sudo apt-get install -y --allow-downgrades ${SWNAME}
	exit_if_fail $? "安装失败"

	cat <<- EOF > /usr/bin/mysqld_passwd_root
		#!/bin/bash
		# ubuntu 24.04 更改mysql中root用户的密码

		if [ \$UID -ne 0 ]; then
			echo "此脚本需要root权限运行，请在指令前面添加sudo "
			exit 1
		fi

		DEFUSR=\`cat /etc/mysql/debian.cnf|grep user    |head -n 1|cut -b 12- \`
		DEFPWD=\`cat /etc/mysql/debian.cnf|grep password|head -n 1|cut -b 12- \`

		# echo "默认用户：\$DEFUSR"
		# echo "默认密码：\$DEFPWD"

		echo "正在设置mysql.root用户的密码，请输入新密码："
		read NEWPWD
		echo "update user set plugin='mysql_native_password' where user='root';"					>  /etc/mysql/zztmp.sql
		echo "FLUSH PRIVILEGES;"																	>> /etc/mysql/zztmp.sql
		echo "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '\$NEWPWD';"	>> /etc/mysql/zztmp.sql
		echo "FLUSH PRIVILEGES;"																	>> /etc/mysql/zztmp.sql

		# sudo sed -i 's|@@@@@@@@@@|\$NEWPWD|g' /etc/apt/sources.list

		mysql -u\$DEFUSR -p\$DEFPWD mysql < /etc/mysql/zztmp.sql
		rlt=\$?
		rm -rf /etc/mysql/zztmp.sql

		echo ""
		if [ \$rlt -eq 0 ]; then
			echo "密码设置成功：\$NEWPWD"
		else
			echo "密码设置失败，请确认mysql-server是否已经启动"
		fi

	EOF
	chmod a+x /usr/bin/mysqld_passwd_root

	gxmessage -title "提示" "安装已完成"  -center &
fi
